<?php

class wms_ctl_admin_receipts_outer extends wms_ctl_admin_receipts_print {

    var $name        = "发货中心";
    var $workground  = "wms_center";
    var $dlyCorp_tab = 'show';


    public function _views() {
        return array();
    }

    /**
     * 第三方发货单列表
     *
     * @author chenping<chenping@shopex.cn>
     **/
    public function index()
    {
        if (isset($_POST['delivery_bn']) && $_POST['delivery_bn']) {
            $deliveryObj = app::get('ome')->model('delivery');
            $rows = $deliveryObj->getParentIdBybn($_POST['delivery_bn']);
            if ($rows) {
                foreach ($rows as $val) {
                    $deliveryId[] = $val['parent_id'];
                }
                $filter['extend_delivery_id'] = $deliveryId;
            }
        }
        $filter['type'] = 'normal';

        //分析status的filter条件
        //$tmp_filter = $this->analyseStatus($_GET['status']);
        $tmp_filter=array();
        $filter = array_merge($filter, $tmp_filter);

        // $filter['shop_id'] = $this->shopIds;
        $filter['status'] = '0';
        // $filter['todo']='4';
        $filter['process_status']=array(0,1);
        $filter['disabled']='false';
        $filter['is_ship']='true';
        $filter['is_form']='true';

        $oBranch = app::get('ome')->model('branch');
        //所有第三方仓
        $outerBranch = array();
        $tmpBranchList = $oBranch->getList('branch_id',array('owner'=>'2'));
        foreach ($tmpBranchList as $key => $value) {
            $outerBranch[] = $value['branch_id'];
        }
        unset($tmpBranchList);
         # 发货配置
        $deliCfgLib = kernel::single('wms_delivery_cfg');
        //获取操作员管辖仓库
        // $is_super = kernel::single('desktop_user')->is_super();
        // if (!$is_super) {
        //     $branch_ids = $oBranch->getBranchByUser(true);
        //     if ($branch_ids) {
        //         $filter['ext_branch_id'] = $_POST['branch_id'] ? $_POST['branch_id'] : $branch_ids;

        //         $filter['ext_branch_id'] = array_intersect($filter['ext_branch_id'], $outerBranch);
        //     } else {
        //         $filter['ext_branch_id'] = 'false';
        //     }
        // } else {
        //     $filter['ext_branch_id'] = $outerBranch;
        // }


        $params = array(
            'title'                  => '快递揽收导入',
            'actions'                => array(
                array(
                    'label'  => '快递揽收导入模板',
                    'href' => 'index.php?app=wms&ctl=admin_receipts_outer&act=exportTemplate',
                    'target' => '_blank',
                ),
                array(
                    'label'  => '快递揽收导入',
                    'href'   => 'index.php?app=wms&ctl=admin_receipts_outer&act=outerimport',
                    'target' => 'dialog::{title:\'快递揽收导入\'}',
                ),

                array(
                    'label'  => '导出',
                    'submit' => 'index.php?app=wms&ctl=admin_receipts_outer&act=index&action=export&btype=2',
                    'target' => 'dialog::{width:400,height:170,title:\'导出\'}',
                ),

                 'stock' => array(
                    'label' => '打印备货单',
                    'submit' => 'index.php?app=wms&ctl=admin_receipts_print&act=toPrintStock' . $attach,
                    'target' => "_blank",
                ),
                'delie' => array(
                    'label' => '打印发货单',
                    'submit' => 'index.php?app=wms&ctl=admin_receipts_print&act=toPrintMerge' . $attach,
                    'target' => '_blank',
                ),
                'merge' => array(
                    'label' => '联合打印',
                    'submit' => 'index.php?app=wms&ctl=admin_receipts_print&act=toMergePrint' . $attach,
                    'target' => '_blank',
                ),
                // 'expre' =>array(
                //         'label' => '打印快递单',
                //         'submit' => 'index.php?app=wms&ctl=admin_receipts_print&act=toPrintShip' . $attach,
                //         'target' => '_blank',
                //     ),
                'expre' => array(
                    'label' => '打印快递单',
                    'submit' => 'index.php?app=wms&ctl=admin_receipts_print&act=toPrintExpre&status=0&logi_id=&sku=' . $attach,
                    'target' => '_blank',
                ),
            ),
            'base_filter'            => $filter,
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag'    => false,
            'use_buildin_recycle'    => false,
            'use_buildin_export'     => false,
            'use_buildin_import'     => false,
            'use_buildin_filter'     => true,
            'use_view_tab'           => true,
            //'object_method'          => array('count' => 'count_logi_no', 'getlist' => 'getlist_logi_no'),
        );
        //选择显示打印的按钮
        $showStockBtn = $deliCfgLib->analyse_btn_status('stock',$sku);
        if ($showStockBtn == false) {
            unset($params['actions']['stock']);
        }
        $showDelieBtn = $deliCfgLib->analyse_btn_status('delie',$sku);
        if ($showDelieBtn == false) {
            unset($params['actions']['delie']);
        }
        $showMergeBtn = $deliCfgLib->analyse_btn_status('merge',$sku);
        if ($showMergeBtn == false) {
            unset($params['actions']['merge']);
        }
        $is_export = kernel::single('desktop_user')->has_permission('process_receipts_print_export');
        if(!$is_export){
            unset($params['actions']['export']);
        }
        $is_toPrintShip = kernel::single('desktop_user')->has_permission('wms_ctl_admin_toPrintShip');
         if(!$is_toPrintShip){
            unset($params['actions']['expre']);
        }
        if(!isset($_GET['action'])) {
            $panel = new desktop_panel($this);
            $panel->setId('delivery_finder_top');
            $panel->setTmpl('admin/finder/finder_panel_filter.html');
            $panel->show('wms_mdl_delivery_outerlogi', $params);
        }
        $this->finder('wms_mdl_delivery_outerlogi',$params);
    }

    function outerimport(){

        echo $this->page('admin/import/import.html');
    }
    #快递揽收导入
    public function doImport(){
        $return = $this->_localSaveFile();
        $data = $return['data'];
        if(!$data){
            echo json_encode(array('result' => 'fail', 'msg' => array('导入数据为空')));
            return false;
        }
        if(count($data) > 5000){
            echo json_encode(array('result' => 'fail', 'msg' => array('导入数据应小于5000条')));
            return false;
        }
        $test=app::get('wms')->model('delivery_outerlogi');
        $datalist = array();
        $result   = array();
        $import_data= array();
        foreach ($data as $key => $value) {
            $ret = $test->prepared_import_csv_outerlogin($value[0],$value[1],$key+2,$msg);
            if($ret == false){
                $result[] = $ret;
            }elseif(is_array($ret)){
                $import_data[] = $ret;
            }
            $error_message = $msg['warning'];
            $datalist[$key]['logi_no']  = $value[0];
            $datalist[$key]['logi_name']= $value[1];
        }
        if(in_array(false,$result)){
            echo json_encode(array('result' => 'fail', 'msg' => $error_message));
            return false;
        }
        $test->finish_import_csv($import_data);
        //增加揽收发货日志列表
        $this->add_third_shipping($datalist);
        unset($import_data);
        echo json_encode(array('result' => 'succ', 'msg' => '上传成功'));
        return true;
    }

    #自定义发货模板导出
    public function exportTemplate(){
        if(!empty($_POST['delivery_id'])){
           $filter['delivery_id'] = $_POST['delivery_id'];
        }
        if(isset($_POST['isSelectedAll']) &&  ($_POST['isSelectedAll'] ==  '_ALL_')){
            $filter['isSelectedAll'] = '_ALL_';
        }
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=outer".date('Ymd').".csv");
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $obj_outerlogi = $this->app->model('delivery_outerlogi');
        $title1 = $obj_outerlogi->exportTemplate();
        echo '"'.implode('","',$title1).'"';
        echo "\n";
        if(empty($filter)){
            exit;
        }
        $obj_outerlogi = $this->app->model('delivery_outerlogi');
        $data =  $obj_outerlogi->getOuterData($filter);
        foreach( $data['content'] as $val){
            echo $val;
            echo "\n";
        }
    }
//增加第三方发货日志列表
    public function add_third_shipping($contents) {
            $opInfo = kernel::single('ome_func')->getDesktopUser();
            $data = array(
                'create_time' => time(),//操作时间
                'option_name' => $opInfo['op_name'],//操作人
                'filedata' => json_encode($contents),
            );
            // error_log(var_export($contents,true),3,DATA_DIR.'/666.log');
             app::get('wms')->model('third_shipping')->save($data);

    }
//第三方发货导入列表
    public function third_shipping_list() {
        $this->finder('wms_mdl_third_shipping',array(
            'title'=>'快递揽收导入列表',
            'actions' => array(
                // array('label'=>'导出模板','href'=>'index.php?app=ome&ctl=admin_order_groupon&act=exportOrderTemplate','target'=>'_blank')
            ),
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag'=>false,
            'use_buildin_recycle'=>false,
            'use_buildin_export'=>false,
            'use_buildin_import'=>false,
            'use_buildin_filter'=>true,
            'use_view_tab'      => false,
            // 'base_filter' => $base_filter,
             'orderBy' =>'create_time DESC'
            ));
    }
//第三方导入列表导出csv
    function exportfilecsv(){
        $list = app::get('wms')->model('third_shipping')->dump(array(
                'shipping_id'=>$_GET['shipping_id']),'filedata');
        $faledata = json_decode($list['filedata'],true);
        $filename = date('Ymd').'.csv'; //设置文件名
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $obj_outerlogi = $this->app->model('delivery_outerlogi');
        $title1 = $obj_outerlogi->exportTemplate();
        echo '"'.implode('","',$title1).'"';
        echo "\n";
        foreach( $faledata as $val){
            foreach ($val as $k =>&$v){
                $val[$k]=iconv('utf-8','gb2312',$val[$k]);
            }
            echo '"'.implode('","',$val).'"';
            echo "\n";
        }

    }
private function _localSaveFile(){
       if( !$_FILES['import_file']['name'] ){
            return  kernel::single('ome_func')->getErrorApiResponse("未上传文件");
        }
        $tmpFileHandle = fopen( $_FILES['import_file']['tmp_name'],"r" );

        $mdl = $_POST['model'];
        $app_id = $_POST['app'];

        $oIo = kernel::servicelist('desktop_io');
        foreach( $oIo as $aIo ){
            if( $aIo->io_type_name == substr($_FILES['import_file']['name'],-3 ) ){
                $oImportType = $aIo;
                break;
            }
        }
        unset($oIo);
        if( !$oImportType ){
            return  kernel::single('ome_func')->getErrorApiResponse("导入格式不正确");
        }

        $contents = array();
        $oImportType->fgethandle($tmpFileHandle,$contents);
        fclose($tmpFileHandle);
        unset($contents[0]);

        $tm_contents = array();
        foreach($contents as $row){
            if(!empty($row[0])){
                $tm_contents[] = $row;
            }
        }
        $contents = $tm_contents;

        if(empty($contents)){
            return  kernel::single('ome_func')->getErrorApiResponse("导入数据项为空");
        }else{
            return  kernel::single('ome_func')->getApiResponse($contents);
        }
    }

}